﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using Cost.Services;
using NBlock.Components.Excel;
using NBlock.Core;
using NBlock.MVCExtensions;
using System.Web.Security;

namespace Cost.Controllers
{
    public class UserController : Controller
    {
        #region 构造函数
        UserService _UserService;
        OrgService _OrgService;
        ICostRepository<UserInfo> _Repo;
        IExcelImporter excelImporter;
        public UserController(ICostRepository<UserInfo> repo,
            UserService userService,
            OrgService orgService,
            IExcelImporter excelImporter)
        {
            _UserService = userService;
            _OrgService = orgService;
            _Repo = repo;
            this.excelImporter = excelImporter;
        }
        #endregion

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(string Id, string orgId)
        {
            var data = _UserService.GetUserInfo(Id, orgId);
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(string Id)
        {
            var data = _Repo.Find(Id) ?? new UserInfo();
            TryUpdateModel(data);
            _UserService.SaveUser(data);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult Delete(string Id)
        {
            _Repo.Delete(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteAll(string Ids)
        {
            var items = Ids.Split(',');
            _Repo.DeleteAll(d => items.Contains(d.Id));
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult List(string orgId, nbPageInfo pager, nbSearchCondition where)
        {
            Expression<Func<UserInfo, bool>> filter = null;
            if (!string.IsNullOrEmpty(orgId))
                filter = u => u.OrgId == orgId;

            var pageData = _Repo.GetPageable(pager, filter, where);
            return Json(pager.ToGridData(pageData));
        }

        [HttpPost]
        public JsonResult OrgTree(string Id)
        {
            // 组装组织结构树
            var orgs = _OrgService.GetOrgsByParentId(Id);
            var list = CommonLogic.GetSubOrgTree(Id, orgs);

            // 如果为空，则增加所有用户这个虚拟节点，显示所有用户
            if (Id == null)
            {
                var childNode = new nbJsonTreeNode();
                childNode.id = "";
                childNode.text = "所有用户";
                childNode.value = "";
                list.Add(childNode);
            }

            return Json(list);
        }

        public JsonResult ValidUserCode(string Id, string UserCode)
        {
            return Json(_UserService.IsValidCode(Id, UserCode), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetDefaultUserCode(string name)
        {
            var userCode = string.Empty;
            if (!string.IsNullOrWhiteSpace(name))
            {
                userCode = HZ2PY.ConvertPY(name);
            }
            return Json(nbAjaxMessage.Successful.SetData(userCode));
        }

        [HttpPost]
        public JsonResult SetUserState(string Id)
        {
            var user = _Repo.Find(Id);
            if (user != null)
            {
                user.AccountStateEnum = AccountState.Disabled;
                _Repo.Update(user);
            }
            return Json(nbAjaxMessage.Successful);
        }

        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public JsonResult ChangePassword(string oldPwd,string newPwd)
        {
            string userId = nbUserContext.Current.CurrentUser.UserId;
            string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(oldPwd, "md5");
            var data = _Repo.Find(u => u.Id == userId && u.Password == pwd);
            if (data != null)
            {
                data.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(newPwd, "md5"); 
                _UserService.SaveUser(data);
                return Json(nbAjaxMessage.Successful);
            }
            else
            {
                return Json(new nbAjaxMessage
                {
                    IsSuccess = false,
                    Msg = "当前密码是否记错了，好好想想！",
                });
            }
        }

        #region 用户导入
        public ActionResult Import(string excelKey)
        {
            ViewBag.TemplateUrl = excelImporter.GetExcelTemplateUrl(excelKey);
            ViewBag.ExcelKey = excelKey;
            return View();
        }

        [HttpPost]
        public nbFileUploadJsonResult Import(HttpPostedFileBase file, string ExcelKey, string UpdateMode)
        {
            try
            {
                // 保留导入文档，以便后续检查
                var path = Server.MapPath("~/Upload/") + System.IO.Path.GetFileName(file.FileName).Replace(".", "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".");
                file.SaveAs(path);

            }
            catch (Exception ex)
            {
                // TODO 记录日志
            }

            var data = excelImporter.Import(file, ExcelKey);
            foreach (var row in data.RepeatData.Rows)
            {
                var user = row.ToEntity<UserInfo>();
                _UserService.SaveUser(user);
            }
            return new nbFileUploadJsonResult { Data = nbAjaxMessage.Successful };
        }

        #endregion
    }
}
